from rest_framework import serializers

from book.models import BookInfo, HeroInfo

class HeroSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    hname = serializers.CharField()
    hgender = serializers.IntegerField(required=False)
    hcomment = serializers.CharField(required=False)
    hbook_id = serializers.IntegerField(write_only=True)

    def create(self, validated_data):
        return HeroInfo.objects.create(**validated_data)


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    btitle = serializers.CharField()
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField(required=False)
    bcomment = serializers.IntegerField(required=False)

    def create(self, validated_data):
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance
